import Vue from 'vue'
import VueRouter from 'vue-router'
// 静态路由数据
import constantRouterMap from './routes'

// 进度条
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'

import store from '@/store/index'
import util from '@/libs/util.js'

Vue.use(VueRouter)
//解决编程式路由往同一地址跳转时会报错的情况
const originalPush = VueRouter.prototype.push;
const originalReplace = VueRouter.prototype.replace;
//push
VueRouter.prototype.push = function push(location, onResolve, onReject) {
	if (onResolve || onReject) return originalPush.call(this, location, onResolve, onReject)
	return originalPush.call(this, location).catch(err => err)
}
//replace
VueRouter.prototype.replace = function push(location, onResolve, onReject) {
	if (onResolve || onReject) return originalReplace.call(this, location, onResolve, onReject)
	return originalReplace.call(this, location).catch(err => err)
}
// 导出路由 在 main.js 里使用
const router = new VueRouter({
	// mode: 'history',
	routes: constantRouterMap
})

const whiteList = ['/login','/error/404'];
let count = 0;

/**
 * 路由拦截
 * 权限验证
 */
router.beforeEach(async (to, from, next) => {
	// 判断cookie里是否存有token作为验证是否登录的条件
	const token = util.cookies.get('Mema-Token');
	const hasToken = token && token !== 'undefined';
	console.log(hasToken);
	if(!hasToken){
		// 没有登录的时候跳转到登录界面
		count = 0;
		NProgress.done();
		if(to.path=='/login'){
			next();
		}else{
			console.log('===没有token跳登录页===');
			next('/login');
		}
		return
	}
	// 根据routers的值判断动态的路由菜单是否已经加载完成
	console.log(58,!store.getters.permission.isDynamicAddRoute)
	if(!store.getters.permission.isDynamicAddRoute) {
		await store.dispatch('d2admin/permission/generateRoutes');
	}
	console.warn('=====路由拦截=====');
	console.log(from);
	console.log(to);
	if(to.name == '404'){
		console.warn('404==========');
		next({replace: true});
		NProgress.done();
		return
	}
	//判断有没有菜单路由信息
	const menuList = util.session.get('menuList')||[];
	console.log('路由菜单：'+menuList.length);
	// 进度条
	NProgress.start()
	if (whiteList.includes(to.path)||!to.path) {
		// 在免登录白名单，直接进入
		console.warn('在免登录白名单，直接进入');
		next({replace: true})
		NProgress.done()
	} else {
		if (menuList.length === 0) {
			console.warn('=====无任何菜单权限=====');
			store.dispatch('d2admin/account/logout', {msg: '无任何菜单权限，请刷新页面或联系系统管理员'}).then(() => {});
			NProgress.done();
			count = 0;
			return
		}
		console.log(count);
		// 无响应,直接退出跳登录页
		if (count >= 10) {
			store.dispatch('d2admin/account/logout').then(r => {})
			count = 0;
			NProgress.done();
			return
		}
		count++
		
		console.log('=====动态的菜单路由已经加载完成====='+store.getters.permission.isDynamicAddRoute);
		if(store.getters.permission.isDynamicAddRoute){
			try {
				// 确认已经加载多标签页数据 https://github.com/d2-projects/d2-admin/issues/201
				await store.dispatch('d2admin/page/isLoaded')
				// 确认已经加载组件尺寸设置 https://github.com/d2-projects/d2-admin/issues/198
				await store.dispatch('d2admin/size/isLoaded')
				// 关闭搜索面板
				store.commit('d2admin/search/set', false)
				// console.warn('已经登录，根据后台返回菜单生成路由');
				console.log(from.query);
				console.warn('去哪里==='+to.path);
				console.warn('来自哪里==='+from.path);
				const redirect = decodeURIComponent(from.query.redirect || to.path);
				if(to.path === '/index'||from.path == '/login'){
					next({replace: true});
				}else{
					if(to.meta.query){
						next({replace: true});
						NProgress.done();
						count = 0;
					}else{
						console.warn('====meta空白====');
						next({
							...to,
							replace: true
						})
						NProgress.done();
						count++;
					}
				}
			} catch (err) {
				next({
					path: '/login'
				})
				NProgress.done();
				count = 0;
			}
		}
	}
})

router.afterEach(to => {
	if (to.path=='/login') return;
	// 进度条
	NProgress.done();
	console.warn('====路由打开一个新页面====');
	console.log(to);
	// 多页控制 打开新的页面
	store.dispatch('d2admin/page/open', to).then(() => {}).catch(err => {
		next({
			path: '/'
		})
	});
	// 更改标题
	util.title(to.meta.title)
})

export default router